package com.hz.framework.MyAction;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
//import org.apache.struts2.interceptor.SessionAware;
import com.hz.framework.MyBean.AllPageBean;
import com.hz.framework.MyBean.PageBean;
import com.hz.framework.MyBean.NewPageBean;
import com.hz.framework.MyInterFace.SystemInterFace;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 公共action 继承DispatchAction
 * 每创建一个新的action继承BaseAction便可进行自动分配action
 * */
public class BaseAction extends ActionSupport implements SystemInterFace,ServletRequestAware,ServletResponseAware {
	
	public BaseAction() {
		getResponse().setCharacterEncoding(getRequest().getCharacterEncoding());
	}
	
	/**	实现接口获得request,response对象; **/
	public HttpServletResponse response;
	public HttpServletRequest request;
	
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	/**	----- **/
	
	/**	通过静态方法获得request,response对象; **/
	public HttpServletResponse getResponse(){
		HttpServletResponse response = ServletActionContext.getResponse();
		return response;
	}
	public HttpServletRequest getRequest(){
		HttpServletRequest request = ServletActionContext.getRequest();
		return request;
	}
	/**	----- **/
	
	public boolean notNull(String str){
		if(null==str||"".equals(str.trim())){
			return false;
		}else{
			return true;
		}
	}
	//判断对象是null转成 "";
	public static String isnull(Object str){
		return (String) (str==null?"":str);
    }
	public Object convert(Object target, Object o) throws Exception {
		if (o == null || target == null) {
			return null;
		}
		BeanUtils.copyProperties(target, o);
		return target;
	}
	/** 传字段数组返回List对象，包含页面多条数据内容（不要包含ID） */
	public List<Map<String, String>> dogetList(HttpServletRequest request,String[] field){
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        int num=request.getParameterValues(field[0]).length;
        for(int i=0;i<num;i++){
            Map<String, String> map = new HashMap<String, String>();
            for(int j=0;j<field.length;j++){
            	String value = request.getParameterValues(field[j])==null?"":request.getParameterValues(field[j])[i];
    		    if("null".equalsIgnoreCase(value))value="";
    		    map.put(field[j],value);
            }
            list.add(map);
        }
        return list;
    }    
	/** 传字段数组返回Map对象，包含页面一条数据内容（不要包含ID） */
	public Map<String, String> dogetMap(HttpServletRequest request,String[] field){
		Map<String, String> map = new HashMap<String, String>();
		for(int i=0;i<field.length;i++){
			String value = request.getParameter(field[i])==null?"":request.getParameter(field[i]);
		    if("null".equalsIgnoreCase(value))value="";
		    map.put(field[i],value);
		}
        return map;
    }
    

	/**
	 *  Java  sql分页 参数: request对象 , 要放到的作用域的名称 , sql语句 , 每页显示数据条数(可不传)
	 * */
	PageBean spd = null;
	public void doSqlSearchList(HttpServletRequest request,String listName, String sql,int pagecount){
		try {
			String action = request.getParameter("action");
			String order = request.getParameter("order")==null?"": request.getParameter("order");
			String taxis = request.getParameter("taxis")==null||"".equals(request.getParameter("taxis"))?"": request.getParameter("taxis");
			if(!"".equals(order)){
				if(sql.lastIndexOf("order")!=-1){
					String[] sqls=sql.split("order ");
					if("".equals(taxis)||"asc".equals(taxis)){
						taxis="asc";
					}else{
						taxis="desc";
					}
					sql=sqls[0]+" order by "+order+" "+taxis;
				}else{
					if("".equals(taxis)||"asc".equals(taxis)){
						taxis="asc";
					}else{
						taxis="desc";
					}
					sql+=" order by "+order+" "+taxis;
				}
			}
			spd = new PageBean(sql,pagecount);
			String page = request.getParameter("page");
			int ln = 1;
			//把当前页数转型
			if(page != null && !"".equals(page)){
				ln = Integer.parseInt(page.trim()) ;
			}
			if (action == null||"".equals(action)) {
				request.setAttribute(listName, spd.getBooks());
			} else {
				if (action == "nextPage" || "nextPage".equals(action)) {
					request.setAttribute(listName, spd.getIndexPage(String.valueOf(ln+1)));
				}
				if (action == "previousPage" || "previousPage".equals(action)) {
					request.setAttribute(listName, spd.getIndexPage(String.valueOf(ln-1)));
				}
				if (action == "index" || "index".equals(action)) {
					String leafNumber = request.getParameter("leafNumber");
					request.setAttribute(listName, spd.getIndexPage(leafNumber));
				}
			}
			request.setAttribute("order", order);
			request.setAttribute("taxis", taxis);
			//request.setAttribute("pagesss", "pagesss");
			request.setAttribute("page", spd);
		} catch (Exception e) {
		}
	}
	public void doSqlSearchList(HttpServletRequest request,String listName, String sql){
		this.doSqlSearchList(request , listName , sql , 0);
	}
	
	/**
	 *  Java  Hql分页  参数: request对象 , 要放到的作用域的名称 , hql语句 , 每页显示数据条数(可不传)
	 * */
	NewPageBean npd = null;
	public void doHqlSearchList(HttpServletRequest request,String listName, String SearcHql,int pagecount) throws Exception {
		try {
			String action = request.getParameter("action");
			String order = request.getParameter("order")==null?"": request.getParameter("order");
			String taxis = request.getParameter("taxis")==null||"".equals(request.getParameter("taxis"))?"": request.getParameter("taxis");
			if(!"".equals(order)){
				if(SearcHql.lastIndexOf("order")!=-1){
					String[] sqls=SearcHql.split("order ");
					if("".equals(taxis)||"asc".equals(taxis)){
						taxis="asc";
					}else{
						taxis="desc";
					}
					SearcHql=sqls[0]+" order by "+order+" "+taxis;
				}else{
					if("".equals(taxis)||"asc".equals(taxis)){
						taxis="asc";
					}else{
						taxis="desc";
					}
					SearcHql+=" order by "+order+" "+taxis;
				}
			}
			npd = new NewPageBean(SearcHql,pagecount);
			String page = request.getParameter("page");
			int ln = 1;
			//把当前页数转型
			if(page != null && !"".equals(page)){
				ln = Integer.parseInt(page.trim()) ;
			}
			
			if (action == null||"".equals(action)) {
				request.setAttribute(listName, npd.getBooks());
			} else {
				if (action == "nextPage" || "nextPage".equals(action)) {
					request.setAttribute(listName, npd.getIndexPage(String.valueOf(ln+1)));
				}
				if (action == "previousPage" || "previousPage".equals(action)) {
					request.setAttribute(listName, npd.getIndexPage(String.valueOf(ln-1)));
				}
				if (action == "index" || "index".equals(action)) {
					String leafNumber = request.getParameter("leafNumber");
					request.setAttribute(listName, npd.getIndexPage(leafNumber));
				}
			}
			request.setAttribute("order", order);
			request.setAttribute("taxis", taxis);
			//request.setAttribute("pagesss", "pagesss");
			request.setAttribute("pagenew", npd);
		} catch (Exception e) {
		}
	}
	public void doHqlSearchList(HttpServletRequest request,String listName, String SearcHql) throws Exception {
		doHqlSearchList( request, listName,  SearcHql, 0);
	}
	
	/**
	 *  Java  所有情况分页 参数: request对象 , 要放到的作用域的名称 , sql语句 或 List集合 , flag分页形式("sql","hql","jdbc","list") , 每页显示数据条数(可不传)
	 * 	注：List 集合分页没有排序功能
	 * */
	AllPageBean apd = null;
	public void doAllSearchList(HttpServletRequest request,String listName, Object sqlList , String flag ,int pagecount){
		try {
			String sql="";
			String action = request.getParameter("action");
			String order = request.getParameter("order")==null?"": request.getParameter("order");
			String taxis = request.getParameter("taxis")==null||"".equals(request.getParameter("taxis"))?"": request.getParameter("taxis");
			if(flag.equals("list")){
				//如果是结果集分页
				apd = new AllPageBean((List)sqlList, flag, pagecount);
			}else{
				//正常查询语句分页
				sql = sqlList.toString();
				if(!"".equals(order)){
					if(sql.lastIndexOf("order")!=-1){
						String[] sqls=sql.split("order ");
						if("".equals(taxis)||"asc".equals(taxis)){
							taxis="asc";
						}else{
							taxis="desc";
						}
						sql=sqls[0]+" order by "+order+" "+taxis;
					}else{
						if("".equals(taxis)||"asc".equals(taxis)){
							taxis="asc";
						}else{
							taxis="desc";
						}
						sql+=" order by "+order+" "+taxis;
					}
				}
				apd = new AllPageBean(sql ,flag ,pagecount);
			}
			
			String page = request.getParameter("page");
			int ln = 1;
			//把当前页数转型
			if(page != null && !"".equals(page)){
				ln = Integer.parseInt(page.trim()) ;
			}
			if (action == null||"".equals(action)) {
				request.setAttribute(listName, apd.getBooks());
			} else {
				if (action == "nextPage" || "nextPage".equals(action)) {
					request.setAttribute(listName, apd.getIndexPage(String.valueOf(ln+1)));
				}
				if (action == "previousPage" || "previousPage".equals(action)) {
					request.setAttribute(listName, apd.getIndexPage(String.valueOf(ln-1)));
				}
				if (action == "index" || "index".equals(action)) {
					String leafNumber = request.getParameter("leafNumber");
					request.setAttribute(listName, apd.getIndexPage(leafNumber));
				}
			}
			request.setAttribute("order", order);
			request.setAttribute("taxis", taxis);
			//request.setAttribute("pagesss", "pagesss");
			request.setAttribute("page", apd);
		} catch (Exception e) {
		}
	}
	public void doAllSearchList(HttpServletRequest request,String listName, Object sqlList , String flag ){
		this.doAllSearchList(request , listName , sqlList , flag, 0);
	}
	
	/***************************************************************************
	 * reponse 打印输出到页面
	 * @param cs
	 */
	public void output(CharSequence cs){
		
		PrintWriter out=null;
		try {
			out = response.getWriter();
			out.append(cs);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			out.flush();
			out.close();
		}
	}
	
	private String action;
	private String leafNumber;
	private String order;
	private String page;
	private String taxis;
	private String thisUrl;
	private String npage;
	public String getNpage() {
		return npage;
	}
	public void setNpage(String npage) {
		this.npage = npage;
	}
	public String getAction() {
		return action;
	}
	public void setAction(String action) {
		this.action = action;
	}
	public String getLeafNumber() {
		return leafNumber;
	}
	public void setLeafNumber(String leafNumber) {
		this.leafNumber = leafNumber;
	}
	public String getOrder() {
		return order;
	}
	public void setOrder(String order) {
		this.order = order;
	}
	public String getPage() {
		return page;
	}
	public void setPage(String page) {
		this.page = page;
	}
	public String getTaxis() {
		return taxis;
	}
	public void setTaxis(String taxis) {
		this.taxis = taxis;
	}
	public String getThisUrl() {
		return thisUrl;
	}
	public void setThisUrl(String thisUrl) {
		this.thisUrl = thisUrl;
	}
}
